﻿using B.S.BaseData.Api.Write.Applicantion.Command;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.Handler
{
    public class RoleAddCommandHandler : IRequestHandler<RoleAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _rolerepository;
        private readonly IBaseRepository<RolePermissionsModel> _rolepermissionrepository;
        public RoleAddCommandHandler(IBaseRepository<RoleModel> rolerepository, IBaseRepository<RolePermissionsModel> rolepermissionrepository)
        {
            _rolerepository = rolerepository;
            _rolepermissionrepository = rolepermissionrepository;
        }
        public async Task<APIResult<int>> Handle(RoleAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            result.Code = ApiEnum.Success;
            result.Msg = "角色添加成功";
            var list=new RoleModel();
            list.RoleName=request.roleName;
            list.IsDeleted=false;
            list.Id=YitIdHelper.NextId();
            await _rolerepository.CreateAsync(list);
            int c = 0;

            var ids= request.Qxsz.Split(",");
            foreach (var item in ids)
            {
                RolePermissionsModel model = new RolePermissionsModel();
                model.Id=YitIdHelper.NextId();
                model.RoleId=list.Id;
                model.PermissionsId = Convert.ToInt64(item);

                await _rolepermissionrepository.CreateAsync(model);
                c++;
            }
            result.Data = c;
            return await Task.FromResult(result);
        }
    }
}
